﻿using Microsoft.EntityFrameworkCore;
using NewFormatProject.Infrastructure.Atrributes;
using NewFormatProject.Infrastructure.Dto.Requests.Objects;
using NewFormatProject.Infrastructure.Dto.Responses;
using NewFormatProject.Infrastructure.EFCore;
using NewFormatProject.Server.Instances.Extends.Requests;
using NewFormatProject.Server.EFCore;
using NewFormatProject.Server.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NewFormatProject.Infrastructure.Dto.Responses.Objects;
using NewFormatProject.Server.Instances.Extends.Entitys;

namespace NewFormatProject.Server.Instances
{
    internal class DepartmentIOC
    {
        public DepartmentServerEF departmentServerEF { get; set; }
    }
    [InjectClass]
    public class DepartmentServer : IDepartmentServer
    {
        DepartmentIOC _departmentIOC;
        public DepartmentServer(DbContext context)
        {
            _departmentIOC = new DepartmentIOC()
            {
                departmentServerEF = new DepartmentServerEF(context)
            };
        }

        public async Task<ResponseApiDto> Add(RequestSysDepartmentsDto dto)
        {
            return ResponseApiDto.Create(await _departmentIOC.departmentServerEF.Add(dto.ToEntity()));
        }

        public async Task<ResponseApiDto> Delete(RequestSysDepartmentsDto department)
        {
            return ResponseApiDto.Create(await _departmentIOC.departmentServerEF.Delete(department.ToEntity()));
        }

        public async Task<ResponseApiDto> Tree()
        {
            var data = await _departmentIOC.departmentServerEF.Query().ToListAsync();
            return ResponseApiDto.Success("成功了", GetTree(data.Where(d => d.DParentId == null).ToList(), data));
        }

        public async Task<ResponseApiDto> Update(RequestSysDepartmentsDto department)
        {
            return ResponseApiDto.Create(await _departmentIOC.departmentServerEF.UpdateAllProperNotNull(department.ToEntity()));
        }

        private List<ResponseSysDepartmentsDto> GetTree(List<SysDepartments> roots, List<SysDepartments> data)
        {
            List<ResponseSysDepartmentsDto> result = new List<ResponseSysDepartmentsDto>();
            foreach (var root in roots)
            {
                result.Add(root.ToResponseDto());
            }
            foreach (var res in result)
            {
                res.children = GetTree(data.Where(d => d.DParentId == res.id).ToList(), data);
            }
            return result;
        }
    }
}
